using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Windows;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CodRevit.Handlers;
using System.Diagnostics;

namespace CodRevit.ViewModels
{
    public partial class ExportScheduleViewModel : ObservableObject
    {
        private readonly UIApplication _uiApp;
        private readonly ExternalEvent _externalEvent;
        private readonly ExportScheduleHandler _handler;
        private readonly List<ViewSchedule> _allSchedules;

        public ExportScheduleViewModel(UIApplication uiApp, ExternalEvent externalEvent, ExportScheduleHandler handler, List<ViewSchedule> schedules)
        {
            _uiApp = uiApp;
            _externalEvent = externalEvent;
            _handler = handler;
            _allSchedules = schedules;

            // 初始化明细表列表
            InitializeScheduleItems();
            
            // 设置默认导出路径
            SetDefaultExportPath();
            
            StatusMessage = $"找到 {_allSchedules.Count} 个明细表，请选择要导出的明细表";
        }

        [ObservableProperty]
        private ObservableCollection<ScheduleItem> _scheduleItems = new();

        [ObservableProperty]
        private string _exportPath = string.Empty;

        [ObservableProperty]
        private string _statusMessage = string.Empty;

        [ObservableProperty]
        private bool _isExporting = false;

        [ObservableProperty]
        private ObservableCollection<string> _exportedSchedules = new();

        [ObservableProperty]
        private bool _selectAll = false;

        [RelayCommand]
        private void Export()
        {
            try
            {
                var selectedSchedules = ScheduleItems.Where(s => s.IsSelected).Select(s => s.Schedule).ToList();
                
                if (!selectedSchedules.Any())
                {
                    StatusMessage = "请至少选择一个明细表";
                    return;
                }

                if (string.IsNullOrEmpty(ExportPath))
                {
                    StatusMessage = "请设置导出路径";
                    return;
                }

                // 确保导出目录存在
                var directory = Path.GetDirectoryName(ExportPath);
                if (!Directory.Exists(directory))
                {
                    try
                    {
                        Directory.CreateDirectory(directory);
                    }
                    catch (Exception ex)
                    {
                        StatusMessage = $"无法创建导出目录: {ex.Message}";
                        return;
                    }
                }

                IsExporting = true;
                StatusMessage = $"正在导出 {selectedSchedules.Count} 个明细表...";
                ExportedSchedules.Clear();

                // 配置处理器参数
                _handler.SetParameters(selectedSchedules, ExportPath, this);

                // 执行外部事件
                _externalEvent.Raise();
            }
            catch (Exception ex)
            {
                StatusMessage = $"导出失败: {ex.Message}";
                IsExporting = false;
            }
        }

        [RelayCommand]
        private void BrowseExportPath()
        {
            try
            {
                var saveFileDialog = new Microsoft.Win32.SaveFileDialog
                {
                    Title = "选择导出位置",
                    Filter = "Excel文件 (*.xlsx)|*.xlsx",
                    FileName = Path.GetFileName(ExportPath),
                    InitialDirectory = Path.GetDirectoryName(ExportPath)
                };

                if (saveFileDialog.ShowDialog() == true)
                {
                    ExportPath = saveFileDialog.FileName;
                }
            }
            catch (Exception ex)
            {
                StatusMessage = $"选择路径时出错: {ex.Message}";
            }
        }

        [RelayCommand]
        private void ToggleSelectAll()
        {
            foreach (var item in ScheduleItems)
            {
                item.IsSelected = SelectAll;
            }
        }

        [RelayCommand]
        private void OpenExportFolder()
        {
            try
            {
                if (!string.IsNullOrEmpty(ExportPath) && File.Exists(ExportPath))
                {
                    var directory = Path.GetDirectoryName(ExportPath);
                    Process.Start("explorer.exe", directory);
                }
            }
            catch (Exception ex)
            {
                StatusMessage = $"打开文件夹失败: {ex.Message}";
            }
        }

        /// <summary>
        /// 自动打开导出的Excel文件
        /// </summary>
        /// <param name="filePath">Excel文件路径</param>
        private void OpenExportedFile(string filePath)
        {
            try
            {
                // 检查文件是否存在
                if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath))
                {
                    System.Diagnostics.Debug.WriteLine($"文件不存在，无法打开: {filePath}");
                    return;
                }

                // 使用默认程序打开Excel文件
                var processStartInfo = new ProcessStartInfo
                {
                    FileName = filePath,
                    UseShellExecute = true, // 使用系统默认程序打开
                    Verb = "open"
                };

                Process.Start(processStartInfo);
                System.Diagnostics.Debug.WriteLine($"成功打开Excel文件: {filePath}");
            }
            catch (Exception ex)
            {
                // 如果直接打开失败，尝试使用explorer打开
                try
                {
                    Process.Start("explorer.exe", $"\"{filePath}\"");
                    System.Diagnostics.Debug.WriteLine($"使用explorer打开Excel文件: {filePath}");
                }
                catch (Exception explorerEx)
                {
                    System.Diagnostics.Debug.WriteLine($"打开Excel文件失败: {ex.Message}, Explorer也失败: {explorerEx.Message}");
                    // 不显示错误消息给用户，因为这是一个便利功能，失败了也不影响主要功能
                }
            }
        }

        private void InitializeScheduleItems()
        {
            ScheduleItems.Clear();
            foreach (var schedule in _allSchedules.OrderBy(s => s.Name))
            {
                ScheduleItems.Add(new ScheduleItem(schedule));
            }
        }

        private void SetDefaultExportPath()
        {
            try
            {
                var doc = _uiApp.ActiveUIDocument.Document;
                var projectName = Path.GetFileNameWithoutExtension(doc.Title);
                
                // 获取Revit文件的当前目录
                string directory;
                if (!string.IsNullOrEmpty(doc.PathName))
                {
                    directory = Path.GetDirectoryName(doc.PathName);
                }
                else
                {
                    // 如果文档未保存，使用桌面
                    directory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                }

                ExportPath = Path.Combine(directory, $"{projectName}_明细表.xlsx");
            }
            catch (Exception ex)
            {
                // 如果设置默认路径失败，使用桌面
                ExportPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "明细表导出.xlsx");
                System.Diagnostics.Debug.WriteLine($"设置默认导出路径失败: {ex.Message}");
            }
        }

        public void OnExportCompleted(List<string> exportedScheduleNames, string message, string filePath)
        {
            try
            {
                if (Application.Current?.Dispatcher != null)
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        ExportedSchedules.Clear();
                        foreach (var scheduleName in exportedScheduleNames)
                        {
                            ExportedSchedules.Add(scheduleName);
                        }
                        StatusMessage = message;
                        IsExporting = false;
                        
                        // 自动打开导出的Excel文件
                        OpenExportedFile(filePath);
                    });
                }
                else
                {
                    // 回退方案：直接设置属性
                    ExportedSchedules.Clear();
                    foreach (var scheduleName in exportedScheduleNames)
                    {
                        ExportedSchedules.Add(scheduleName);
                    }
                    StatusMessage = message;
                    IsExporting = false;
                    
                    // 自动打开导出的Excel文件
                    OpenExportedFile(filePath);
                }
            }
            catch (Exception ex)
            {
                // 如果Dispatcher调用失败，直接设置属性作为回退
                StatusMessage = message;
                IsExporting = false;
                System.Diagnostics.Debug.WriteLine($"OnExportCompleted异常: {ex.Message}");
                
                // 尝试打开导出的Excel文件
                OpenExportedFile(filePath);
            }
        }

        public void OnExportFailed(string errorMessage)
        {
            try
            {
                if (Application.Current?.Dispatcher != null)
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        StatusMessage = $"导出失败: {errorMessage}";
                        IsExporting = false;
                    });
                }
                else
                {
                    // 回退方案：直接设置属性
                    StatusMessage = $"导出失败: {errorMessage}";
                    IsExporting = false;
                }
            }
            catch (Exception ex)
            {
                // 如果Dispatcher调用失败，直接设置属性作为回退
                StatusMessage = $"导出失败: {errorMessage}";
                IsExporting = false;
                System.Diagnostics.Debug.WriteLine($"OnExportFailed异常: {ex.Message}");
            }
        }
    }

    public partial class ScheduleItem : ObservableObject
    {
        public ScheduleItem(ViewSchedule schedule)
        {
            Schedule = schedule;
            Name = schedule.Name;
            
            // 获取明细表的一些基本信息
            try
            {
                var tableData = schedule.GetTableData();
                var sectionData = tableData.GetSectionData(SectionType.Body);
                RowCount = sectionData.NumberOfRows;
                ColumnCount = sectionData.NumberOfColumns;
                Description = $"{RowCount} 行 × {ColumnCount} 列";
            }
            catch
            {
                Description = "无法获取明细表信息";
            }
        }

        public ViewSchedule Schedule { get; }
        public string Name { get; }
        public string Description { get; }
        public int RowCount { get; }
        public int ColumnCount { get; }

        [ObservableProperty]
        private bool _isSelected = false;
    }
}